package com.walkline.app;

import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

import net.rim.device.api.database.Database;
import net.rim.device.api.database.DatabaseFactory;
import net.rim.device.api.database.DatabaseOptions;
import net.rim.device.api.database.DatabaseSecurityOptions;
import net.rim.device.api.io.URI;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;

import com.walkline.screen.CreditcardRecorderScreen;
import com.walkline.util.sqlite.SQLManager;

public class CreditcardRecorderApp extends UiApplication
{
    public static void main(String[] args) throws Exception
    {
        CreditcardRecorderApp theApp = new CreditcardRecorderApp();       
        theApp.enterEventDispatcher();
    }

    public CreditcardRecorderApp() throws Exception
    {
    	boolean sdCardPresent = false;
    	boolean storePresent = false;
    	String root = null;
    	SQLManager sqlManager = null;

    	Enumeration e = FileSystemRegistry.listRoots();
    	while (e.hasMoreElements())
    	{
    		root = (String)e.nextElement();
    		if (root.equalsIgnoreCase("sdcard/")) {sdCardPresent = true;}
    		if (root.equalsIgnoreCase("store/")) {storePresent = true;}
    	}            

    	if (!storePresent && !sdCardPresent) {
    		UiApplication.getUiApplication().invokeLater(new Runnable()
    		{
    			public void run()
    			{
    				Dialog.alert("This application requires a built-in storage or SD card to be present. Exiting application...");
    				System.exit(0);
    			} 
    		});
    	}

    	String dbLocation = null;
    	if (storePresent) {
            dbLocation = "/store/home/user/Creditcard Recorder/";
    	} else {
    		dbLocation = "/SDCard/Creditcard Recorder/"; 
    	}

    	URI uri = URI.create(dbLocation + CreditcardRecorderConfig.DB_NAME);
    	Database db = DatabaseFactory.openOrCreate(uri, new DatabaseSecurityOptions(false));
    	db.close();

    	FileConnection fileConnection = (FileConnection)Connector.open("file://" + dbLocation + CreditcardRecorderConfig.DB_NAME);    
        if (fileConnection.exists() && fileConnection.fileSize() == 0)
        {
        	db = DatabaseFactory.open(uri);
        	sqlManager = new SQLManager(db);
        	sqlManager.initStructure();
        	db.close();
        }

        db = DatabaseFactory.open(uri, new DatabaseOptions());
        sqlManager = new SQLManager(db);
    	pushScreen(new CreditcardRecorderScreen(sqlManager));
    }
}